package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.View;

import com.blankj.utilcode.util.ArrayUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.media.recorder.AudioRecorder;
import com.stark.piano.lib.widget.PianoConst;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.RecordAdapter;
import flc.ast.databinding.ActivityRecordListBinding;
import flc.ast.dialog.DeleteDialog;
import flc.ast.dialog.RecordDialog;
import flc.ast.dialog.RecordMoreDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;

public class RecordListActivity extends BaseAc<ActivityRecordListBinding> {

    private RecordAdapter recordAdapter;
    private int tmpPos;
    private IAudioPlayer mAudioPlayer;


    @Override
    protected int onCreate() {
        return R.layout.activity_record_list;
    }

    @Override
    protected void initView() {
        mDataBinding.ivRecordListBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        tmpPos = -1;
        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.setListener(new IAudioPlayer.IListener() {
            @Override
            public void onUpdatePlayTime(int curPlayTime, int duration) {
                if (tmpPos != -1) {
                    if (curPlayTime == 0) {
                        recordAdapter.getItem(tmpPos).setSelected(true);
                        recordAdapter.notifyItemChanged(tmpPos);
                    }
                }
            }

            @Override
            public void onPlayChange(boolean isPlaying) {
                if (tmpPos != -1) {
                   if (!isPlaying){
                       recordAdapter.getItem(tmpPos).setSelected(isPlaying);
                       recordAdapter.notifyItemChanged(tmpPos);
                   }
                }
            }
        });
        mDataBinding.rvRecordList.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
        recordAdapter=new RecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.addChildClickViewIds(R.id.ivRecordPlay,R.id.ivRecordMore);
        recordAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        AudioBean item = recordAdapter.getItem(position);
        switch (view.getId()){
            case R.id.ivRecordPlay:
                if (tmpPos == position) {
                    if (item.isSelected()) {
                        mAudioPlayer.pause();
                    } else {
                        mAudioPlayer.resume();
                    }
                } else {
                    if (tmpPos != -1) {
                        if (mAudioPlayer.isPlaying()) {
                            mAudioPlayer.stop();
                        }
                        recordAdapter.getItem(tmpPos).setSelected(false);
                        recordAdapter.notifyItemChanged(tmpPos);
                    }
                    tmpPos = position;
                    mAudioPlayer.play(item.getPath());
                }
                break;
            case R.id.ivRecordMore:
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                }
                recordAdapter.notifyItemChanged(position);
                RecordMoreDialog recordMoreDialog=new RecordMoreDialog(mContext);
                BasePopupView popup = new XPopup.Builder(mContext)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .atView(view)
                        .popupPosition(PopupPosition.Bottom)
                        .hasShadowBg(false) // 去掉半透明背景
                        .asCustom(recordMoreDialog);
                recordMoreDialog.setListener(new RecordMoreDialog.IListener() {
                    @Override
                    public void onClickRename() {
                        showRenameDialog(item);
                    }

                    @Override
                    public void onClickShare() {
                        IntentUtil.shareAudio(mContext,item.getPath());
                    }

                    @Override
                    public void onClickDelete() {
                        DeleteDialog deleteDialog=new DeleteDialog(RecordListActivity.this);
                        deleteDialog.setListener(new DeleteDialog.IListener() {
                            @Override
                            public void onClickConfirm() {
                                if (tmpPos == recordAdapter.getItemPosition(item)) {
                                    tmpPos = -1;
                                }
                                FileUtils.delete(item.getPath());
                                recordAdapter.remove(item);
                                deleteDialog.dismiss();
                                ToastUtils.showShort(R.string.delete_success);
                                if (recordAdapter.getData().size() == 0) {
                                    mDataBinding.tvRecordListNoData.setVisibility(View.VISIBLE);
                                    mDataBinding.rvRecordList.setVisibility(View.GONE);
                                }
                            }
                        });
                        deleteDialog.show();
                    }
                });
                popup.show();
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<AudioBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<AudioBean>> emitter) {
                List<AudioBean> audioBeanList = new ArrayList<>();
                AudioRecorder.getInstance().setRecFolderName(PianoConst.REC_FOLDER);
                List<File> files = FileUtils.listFilesInDir(AudioRecorder.getInstance().getRecFolder());
                if (files.size() > 1) {
                    File[] fileArray = new File[files.size()];
                    files.toArray(fileArray);
                    ArrayUtils.sort(fileArray, new Comparator<File>() {
                        @Override
                        public int compare(File file1, File file2) {
                            return (int) (file2.lastModified() - file1.lastModified());
                        }
                    });
                    files = ArrayUtils.asArrayList(fileArray);
                }
                for (File file : files) {
                    AudioBean audioBean = new AudioBean();
                    audioBean.setPath(file.getPath());
                    audioBean.setName(file.getName());
                    audioBean.setDuration(MediaUtil.getDuration(file.getPath()));
                    audioBean.setDateModified(FileUtils.getFileLastModified(file) / 1000L);

                    audioBeanList.add(audioBean);
                }
                emitter.onNext(audioBeanList);
            }

            @Override
            public void accept(List<AudioBean> obj) {
                if (obj == null || obj.size() == 0) {
                    mDataBinding.tvRecordListNoData.setVisibility(View.VISIBLE);
                    mDataBinding.rvRecordList.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
                    mDataBinding.tvRecordListNoData.setVisibility(View.GONE);

                    recordAdapter.setList(obj);
                }
            }
        });
    }

    private void showRenameDialog(AudioBean item) {
        String fileName = FileUtils.getFileNameNoExtension(item.getPath());
        RecordDialog recordDialog = new RecordDialog(this);
        recordDialog.setListener(new RecordDialog.IListener() {
            @Override
            public void onClickConfirm(String newFileName) {
                if (fileName.equals(newFileName)) {
                    recordDialog.dismiss();
                    return;
                }
                String suffix = FileUtils.getFileExtension(item.getPath());
                boolean hasExit = false;
                for (AudioBean datum : recordAdapter.getData()) {
                    if (datum.getName().equals(newFileName + "." + suffix)) {
                        hasExit = true;
                        break;
                    }
                }
                if (hasExit) {
                    ToastUtils.showShort(R.string.piano_file_name_exist_tip);
                    return;
                }
                RxUtil.create(new RxUtil.Callback<Boolean>() {
                    @Override
                    public void doBackground(ObservableEmitter<Boolean> emitter) {
                        boolean rename = FileUtils.rename(item.getPath(), newFileName + "." + suffix);
                        emitter.onNext(rename);
                    }

                    @Override
                    public void accept(Boolean obj) {
                        item.setName(newFileName + "." + suffix);
                        String dirName = FileUtils.getDirName(item.getPath());
                        item.setPath(dirName + newFileName + "." + suffix);
                        recordAdapter.notifyItemChanged(recordAdapter.getItemPosition(item));
                        recordDialog.dismiss();
                    }
                });
            }
        });
        recordDialog.setCurrentFileName(fileName);
        recordDialog.setType(Content.record_type_rename);
        recordDialog.show();
    }

}